// pages/address/list/index.js
import { reqAddressList, reqDeleteAddress } from '../../../api/address'
import { swipeCellBehavior } from '@/behaviors/swipeCell'

// 获取应用实例
const app = getApp()

Page({
  behaviors: [swipeCellBehavior],
  // 页面的初始数据
  data: {
    addressList: []
  },

  // 删除指定收货地址
  async deleteAddress(event) {
    const { id } = event.currentTarget.dataset

    const modalRes = await wx.modal({
      content: '您确实删除该收货地址吗？'
    })
    if (modalRes) {
      await reqDeleteAddress(id)
      wx.toast({ title: '收货地址删除成功' })
      this.getAddressList()
    }
  },

  // 去编辑页面
  toEdit(event) {
    // 获取id
    const { id } = event.currentTarget.dataset
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },

  // 获取收货地址列表
  async getAddressList() {
    const res = await reqAddressList()
    this.setData({
      addressList: res.data
    })
  },

  // 更新收货地址
  changeAddress(event) {
    if (this.flag !== '1') return
    const addressId = event.currentTarget.dataset.id
    // 根据id从收货地址列表中找到对应的地址详细信息
    const selectAddress = this.data.addressList.find((item) => item.id === addressId)
    if (selectAddress) {
      // 选择地址成功以后 需要赋值给全局共享的数据
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },

  onShow() {
    this.getAddressList()
  },

  onLoad(options) {
    this.flag = options.flag
  }
})
